<?php

class Guest extends CI_Controller {

    function __construct() {
        parent::__construct();
        $level_id = $this->session->userdata('logged_in');
        if ($level_id['level_id'] == null) {
            redirect('user/login', 'refresh');
        }
        if ($level_id['level_id'] == 0) {
            redirect('user', 'refresh');
        }
    }

    function index() {

        $crud = new grocery_CRUD();
		$crud->where('deleted','No');

        $crud->set_table('guest');
        $crud->set_subject('Guest');
        $crud->required_fields('guest_name', 'guest_address', 'guest_phone', 'guest_type');
        $crud->columns('guest_name', 'guest_ktp', 'nationality', 'guest_address', 'guest_phone', 'guest_type', 'pic_agency');
        $crud->order_by('guest_id', 'desc');
		
		$crud->unset_add_fields('last_modifier', 'last_modified', 'deleted');
		$crud->unset_edit_fields('last_modifier', 'last_modified', 'deleted');
		
		$crud->add_fields('guest_name', 'pic_agency', 'guest_ktp', 'guest_address', 'guest_phone', 'nationality', 'guest_type', 'guest_desc');
		$crud->edit_fields('guest_name', 'pic_agency', 'guest_ktp', 'guest_address', 'guest_phone', 'nationality', 'guest_type', 'guest_desc');
		
		$crud->callback_after_insert(array($this, 'after_insert'));
		$crud->callback_after_update(array($this, 'after_update'));
		$crud->callback_delete(array($this, 'after_delete'));
		
        $crud->display_as('guest_name', 'Name');
        $crud->display_as('guest_ktp', 'ID Card');
        $crud->display_as('guest_address', 'Address');
        $crud->display_as('guest_phone', 'Phone');
        $crud->display_as('guest_type', 'Guest Type');
        $crud->display_as('pic_agency', 'PIC Agency');
        $crud->display_as('guest_desc', 'Guest Description');
		

        $crud->callback_field('guest_ktp', array($this, 'KTP_desc'));

        $output = (array) $crud->render();
        $output['title'] = 'Guest List';

        $this->load->template('guest/index', $output);
    }

    function KTP_desc($value = '') {
        return '<input type="number" maxlength="16" value="' . $value . '" name="guest_ktp" style="width:auto">';
    }
	
	function after_insert($post, $primary_key){
		$level_id = $this->session->userdata('logged_in');
		$this->db->update('guest', array('last_modifier'=>$level_id['user_id'], 'deleted'=>'No'), array('guest_id'=>$primary_key));
		
	}
	
	function after_update($post, $primary_key){
		$level_id = $this->session->userdata('logged_in');
		$this->db->update('guest', array('last_modifier'=>$level_id['user_id']), array('guest_id'=>$primary_key));
	}
	
	function after_delete($primary_key){
		$level_id = $this->session->userdata('logged_in');
		$this->db->update('guest', array('last_modifier'=>$level_id['user_id'], 'deleted'=>'Yes'), array('guest_id'=>$primary_key));
	}

}
